package cn.gok.hotelback.controller;

import cn.gok.hotelback.entity.RoomOrder;
import cn.gok.hotelback.entity.OrderReview;
import cn.gok.hotelback.service.RoomOrderService;
import cn.gok.hotelback.service.RoomTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import cn.gok.hotelback.entity.User;

@RestController
@RequestMapping("/order")
public class RoomOrderController {
    @Autowired
    private RoomOrderService roomOrderService;
    
    @Autowired
    private RoomTypeService roomTypeService;

    @PostMapping("/create")
    public String createOrder(@RequestBody RoomOrder order) {
        // 生成订单号（时间戳+随机数）
        order.setOrderId(System.currentTimeMillis() + "" + (int)(Math.random()*10000));
        order.setOrderStatus("0"); // 0-已预订
        if (order.getUserId() == null) {
            order.setUserId(1); // 临时默认用户，实际应强制登录
        }
        
        // 自动计算总金额
        float totalAmount = calculateTotalAmount(order);
        order.setTotalAmount(totalAmount);
        
        boolean result = roomOrderService.createOrder(order);
        return result ? "success" : "fail";
    }
    
    /**
     * 计算订单总金额
     * @param order 订单信息
     * @return 总金额
     */
    private float calculateTotalAmount(RoomOrder order) {
        try {
            // 获取房型价格
            float pricePerNight = roomTypeService.getPriceByTypeId(order.getRoomTypeId());
            
            // 解析入住时间字符串，格式如："2025-01-01 至 2025-01-03"
            String checkInTime = order.getCheckInTime();
            String[] dates = checkInTime.split(" 至 ");
            
            if (dates.length == 2) {
                // 解析入住日期和离开日期
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                LocalDate checkInDate = LocalDate.parse(dates[0].trim(), formatter);
                LocalDate checkOutDate = LocalDate.parse(dates[1].trim(), formatter);
                
                // 计算住宿天数
                long days = java.time.temporal.ChronoUnit.DAYS.between(checkInDate, checkOutDate);
                
                // 计算总金额
                float total = pricePerNight * days;
                if (order.getUserId() != null && order.getUserId() > 0) {
                    User user = roomOrderService.getUserById(order.getUserId());
                    if (user != null && user.getLevel() != null && user.getLevel() >= 2 && user.getLevel() <= 8) {
                        float[] discount = {1f, 0.98f, 0.96f, 0.94f, 0.92f, 0.90f, 0.88f, 0.86f};
                        total = total * discount[user.getLevel() - 1];
                    }
                }
                return total;
            }
            
            // 如果解析失败，返回房型价格作为默认值
            return pricePerNight;
        } catch (Exception e) {
            // 异常情况下返回房型价格作为默认值
            return roomTypeService.getPriceByTypeId(order.getRoomTypeId());
        }
    }

    /**
     * 根据手机号后四位查询未入住订单
     */
    @GetMapping("/listByPhoneSuffix")
    public List<RoomOrder> listByPhoneSuffix(@RequestParam String phoneSuffix) {
        return roomOrderService.findOrdersByPhoneSuffix(phoneSuffix);
    }

    /**
     * 根据用户ID查询订单
     */
    @GetMapping("/list")
    public List<RoomOrder> listByUserId(@RequestParam Integer userId) {
        return roomOrderService.findOrdersByUserId(userId);
    }

    /**
     * 获取所有订单
     */
    @GetMapping("/listAll")
    public java.util.List<RoomOrder> listAllOrders() {
        return roomOrderService.findAllOrders();
    }

    /**
     * 提交订单评价
     */
    @PostMapping("/review")
    public String submitReview(@RequestBody OrderReviewRequest request) {
        boolean result = roomOrderService.submitReview(request.getOrderId(), request.getRating(), request.getContent());
        return result ? "success" : "fail";
    }

    /**
     * 获取用户评价列表
     */
    @GetMapping("/reviews")
    public List<OrderReview> getUserReviews(@RequestParam Integer userId) {
        return roomOrderService.getUserReviews(userId);
    }

    /**
     * 提交追评
     */
    @PostMapping("/review/append")
    public String appendReview(@RequestBody OrderReviewRequest request) {
        boolean result = roomOrderService.appendReview(request.getOrderId(), request.getContent());
        return result ? "success" : "fail";
    }

    /**
     * 更新评价
     */
    @PutMapping("/review/update")
    public String updateReview(@RequestBody UpdateReviewRequest request) {
        boolean result = roomOrderService.updateReview(request.getReviewId(), request.getRating(), request.getContent());
        return result ? "success" : "fail";
    }

    /**
     * 删除评价
     */
    @PostMapping("/review/delete")
    public String deleteReview(@RequestParam Integer reviewId, @RequestParam(required = false, defaultValue = "single") String deleteType) {
        boolean result;
        if ("all".equals(deleteType)) {
            // 删除主体评价时，删除该订单的所有评价
            result = roomOrderService.deleteAllReviewsByReviewId(reviewId);
        } else {
            // 删除单条评价（追评）
            result = roomOrderService.deleteReview(reviewId);
        }
        return result ? "success" : "fail";
    }

    /**
     * 办理入住
     */
    @PostMapping("/checkin")
    public String checkin(@RequestBody CheckinRequest req) {
        boolean ok = roomOrderService.checkin(req.getOrderId(), req.getRoomId(), req.getGuestInfo());
        return ok ? "success" : "fail";
    }

    /**
     * 办理退房
     */
    @PostMapping("/checkout")
    public String checkout(@RequestBody CheckoutRequest req) {
        boolean ok = roomOrderService.checkout(req.getRoomNumber());
        return ok ? "success" : "fail";
    }

    /**
     * 查询房号当前入住订单
     */
    @GetMapping("/checkedinOrder")
    public RoomOrder getCheckedInOrderByRoomNumber(@RequestParam String roomNumber) {
        return roomOrderService.getCheckedInOrderByRoomNumber(roomNumber);
    }

    /**
     * 通过订单ID获取评价
     */
    @GetMapping("/reviewByOrder")
    public OrderReview getReviewByOrder(@RequestParam String orderId) {
        return roomOrderService.getReviewByOrderId(orderId);
    }

    public static class CheckinRequest {
        private String orderId;
        private Integer roomId;
        private String guestInfo;
        public String getOrderId() { return orderId; }
        public void setOrderId(String orderId) { this.orderId = orderId; }
        public Integer getRoomId() { return roomId; }
        public void setRoomId(Integer roomId) { this.roomId = roomId; }
        public String getGuestInfo() { return guestInfo; }
        public void setGuestInfo(String guestInfo) { this.guestInfo = guestInfo; }
    }

    public static class CheckoutRequest {
        private String roomNumber;
        public String getRoomNumber() { return roomNumber; }
        public void setRoomNumber(String roomNumber) { this.roomNumber = roomNumber; }
    }

    public static class OrderReviewRequest {
        private String orderId;
        private Integer rating;
        private String content;
        
        public String getOrderId() { return orderId; }
        public void setOrderId(String orderId) { this.orderId = orderId; }
        public Integer getRating() { return rating; }
        public void setRating(Integer rating) { this.rating = rating; }
        public String getContent() { return content; }
        public void setContent(String content) { this.content = content; }
    }

    public static class UpdateReviewRequest {
        private Integer reviewId;
        private Integer rating;
        private String content;
        
        public Integer getReviewId() { return reviewId; }
        public void setReviewId(Integer reviewId) { this.reviewId = reviewId; }
        public Integer getRating() { return rating; }
        public void setRating(Integer rating) { this.rating = rating; }
        public String getContent() { return content; }
        public void setContent(String content) { this.content = content; }
    }
} 